package com.my.ry.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSONObject;
import com.my.ry.constant.Constant;
import com.my.ry.entity.User;
import com.my.ry.service.UserService;

@Controller
@RequestMapping("/user")
public class UserController {
	
	@Autowired
	private UserService userService;
	
	/**
	 * 用户登录
	 * @param jsonString
	 * @return
	 */
	@RequestMapping(value = "/login")
	@ResponseBody
	public JSONObject userLogin(String jsonString) {
		JSONObject returnMap = new JSONObject();
		
		try {
			returnMap = userService.userLogin(jsonString);
		} catch (Exception e) {
			e.printStackTrace();
			returnMap = JSONObject.parseObject(Constant.jsonStr_exception);
		}
		
		return returnMap;
	}
	
	
	/**
	 * 用户列表
	 * @param model
	 * @return
	 */
	@RequestMapping(value = "/users")
	@ResponseBody
	public Map<String, Object> getUsers(String jsonString) {
		Map<String, Object> result = new HashMap<>();
		try {
			result = userService.GetUserList(jsonString);
		} catch (Exception e) {
			result = JSONObject.parseObject(Constant.jsonStr_exception);
		}
		
		return result;
	}
	
	@RequestMapping(value = "/add.do", method = RequestMethod.POST)
	public String addUser(User user) throws Exception{
		
		int index = userService.addUser(user);
		System.out.println(index);
		return "redirect:users";
	}
	
	@RequestMapping(value = "/newUser", method = RequestMethod.GET)
	public String userAdd(){
		return "addUser";
	}
	
	
	/**
	 *  列表导出
	 * @throws Exception 
	 */
	@RequestMapping(value = "/exportUserInfo")
	@ResponseBody
	public void exportUserInfo(String jsonString, HttpServletResponse response) throws Exception {
		userService.exportUserInfo(jsonString,response);
	}
	
	/**
	 *  前端导出所需数据
	 * @throws Exception 
	 */
	@RequestMapping(value = "/exportUserInfoList")
	@ResponseBody
	public Map<String, Object> exportUserInfoList(String jsonString) throws Exception {
		Map<String, Object> result = new HashMap<>();
		try {
			result = userService.exportUserInfoList(jsonString);
		} catch (Exception e) {
			result = JSONObject.parseObject(Constant.jsonStr_exception);
		}
		
		return result;
	}
}
